const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const { action, id, status } = event
  const { OPENID } = cloud.getWXContext()

  try {
    switch (action) {
      case 'updateStatus':
        // 验证记录是否属于当前用户
        const record = await db.collection('formData').doc(id).get()
        if (record.data._openid !== OPENID) {
          throw new Error('无权操作此记录')
        }
        
        // 更新状态
        await db.collection('formData').doc(id).update({
          data: {
            status: status,
            updatedAt: db.serverDate()
          }
        })
        
        return { success: true }
        
      default:
        throw new Error('无效的操作类型')
    }
  } catch (err) {
    console.error('云函数错误:', err)
    return { success: false, error: err.message }
  }
}